package com.enterprise.shiro;

import com.enterprise.entity.Resources;
import com.enterprise.entity.User;
import com.enterprise.service.ResourcesService;
import com.enterprise.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;


public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;
    @Resource
    private ResourcesService resourcesService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = principals.toString();
        System.out.println(username);
        User user = new User();
        user.setUsername(username);
        user= userService.login(user);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Resources> resources = resourcesService.getResources(username);
        for (Resources resource:resources){
            info.addStringPermission(resource.getResourcescode());
        }
        return info;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token == null || StringUtils.isBlank((String) token.getPrincipal())) {
            return null;
        }
        User user = new User();
        user.setUsername((String) token.getPrincipal());
        user= userService.login(user);
        if (user == null) {
            throw new IncorrectCredentialsException("认证失败，用户不存在");
        }
        return new SimpleAuthenticationInfo(
                user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getUsername()), getName());
    }

    @Override
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        char[] credentials = (char[]) token.getCredentials();
        String password = String.valueOf(credentials);
        String dbusername = info.getPrincipals().toString();
        String dbpassword = info.getCredentials().toString();
        if (!username.equals(dbusername)  || !password.equals(dbpassword)){
            throw new IncorrectCredentialsException("认证失败，密码错误");
        }
    }
}